package org.jeecgframework.web.system.service.impl;

import com.alibaba.fastjson.JSONObject;
import org.jeecgframework.core.util.HttpUtils;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.web.system.pojo.base.TSRoleUser;
import org.jeecgframework.web.system.pojo.base.TSUser;
import org.jeecgframework.web.system.service.UserService;

import org.hibernate.Criteria;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.jeecgframework.core.common.service.impl.CommonServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;

/**
 * 
 * @author  chrc
 *
 */
@Service("userService")
@Transactional
public class UserServiceImpl extends CommonServiceImpl implements UserService {

	public TSUser checkUserExits(TSUser user){
		return this.commonDao.getUserByUserIdAndUserNameExits(user);
	}
	
	/**
	 * 确认用户存在，CAS登陆用
	 */
	public TSUser checkUserExitsForCas(TSUser user){
		return this.commonDao.getUserByUserIdAndUserNameExitsForCas(user);
	}
	
	public String getUserRole(TSUser user){
		return this.commonDao.getUserRole(user);
	}
	
	public void pwdInit(TSUser user,String newPwd) {
			this.commonDao.pwdInit(user,newPwd);
	}
	
	public int getUsersOfThisRole(String id) {
		Criteria criteria = getSession().createCriteria(TSRoleUser.class);
		criteria.add(Restrictions.eq("TSRole.id", id));
		int allCounts = ((Long) criteria.setProjection(
				Projections.rowCount()).uniqueResult()).intValue();
		return allCounts;
	}
	public JSONObject ectonSingleLogin(TSUser user) throws IOException {
		String uid=user.getUserName();
		String pwd=user.getPassword();
		String loginUrl= ResourceUtil.getConfigByName("singlelogin.test.wwwurl");
		loginUrl=String.format(loginUrl,uid,pwd);
		String result= HttpUtils.get(loginUrl);
		JSONObject json=JSONObject.parseObject(result);
		return json;
	}

	@Override
	public JSONObject ectonNcSingleLogin(TSUser user) {
		String uid=user.getUserName();
		String pwd=user.getPassword();
		String result= HttpUtils.getNcCheckLogin(uid,pwd);
		JSONObject json=JSONObject.parseObject(result);
		return json;
	}

}
